package net.forsalemall.android;

import org.json.JSONObject;

import com.utils.Constants;
import com.utils.HttpUtils;
import com.utils.Utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;

public class SplashActivity extends Activity {

	private long time;
	private static final int SPLASH_SCREEN_DISPLAY_TIME = 2000;

	private String constantData;
	private String deviceDetails;

	@Override
	public void onCreate(Bundle icicle) {
		try {
			super.onCreate(icicle);
			time = System.currentTimeMillis();
			doNext();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void doNext() {
		try {

			if (Utils.isOnline(this)) {
				new AsyncTask<String, String, String>() {
					private boolean isBlocaked;
					private Exception exception = null;

					@Override
					protected void onPreExecute() {
						isBlocaked = true;
					}

					@Override
					protected String doInBackground(String... arg0) {
						try {
							deviceDetails = HttpUtils.getDeviceDetails(true,
									Utils.getDeviceId(SplashActivity.this));
							JSONObject jo = new JSONObject(deviceDetails);
							if (jo.getInt("is_blocked") == 0) {
								isBlocaked = false;
								constantData = HttpUtils.getConstantsData();
								Constants.initConstants(constantData);
								time = SPLASH_SCREEN_DISPLAY_TIME + time
										- System.currentTimeMillis();
								if (time > 0) {
									Thread.sleep(time);
								}
							}
						} catch (Exception e) {
							exception = e;
							e.printStackTrace();
						}
						return null;
					}

					@Override
					protected void onPostExecute(String unused) {

						if (exception != null) {
							showAlertMessage(null,
									exception.getLocalizedMessage());
						} else {

							if (isBlocaked) {
								showAlertMessage(null,
										getString(R.string.blocked_message));
							} else {
								if (constantData != null) {
									if (!isFinishing()) {
										startActivity(new Intent(
												SplashActivity.this,
												HomeActivity.class));
									}
								} else {
									showAlertMessage(null,
											getString(R.string.server_error));
								}
							}
						}

					}
				}.execute();
			} else {
				showAlertMessage(null, getString(R.string.go_online));
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void showAlertMessage(String title, String message) {
		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage(message)
				.setCancelable(false)
				.setPositiveButton(getString(R.string.ok),
						new DialogInterface.OnClickListener() {
							public void onClick(final DialogInterface dialog,
									final int id) {
								finish();
							}
						});
		final AlertDialog alert = builder.create();
		alert.setTitle(title);
		alert.show();
	}
}